package cn.zhentao.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Base64;

/**
 * 图片代理控制器
 * 用于代理获取阿里云OSS图片，解决跨域和防盗链问题
 */
@Slf4j
@RestController
@RequestMapping("/api/image")
@CrossOrigin(origins = "*")
public class ImageProxyController {

    /**
     * 代理获取图片
     */
    @GetMapping("/proxy")
    public ResponseEntity<byte[]> proxyImage(@RequestParam String url) {
        try {
            log.info("代理获取图片: {}", url);
            
            // 验证URL是否为阿里云OSS链接
            if (!url.contains("dashscope-result") || !url.contains("aliyuncs.com")) {
                log.warn("非法的图片URL: {}", url);
                return ResponseEntity.badRequest().build();
            }
            
            // 创建URL连接
            URL imageUrl = new URL(url);
            URLConnection connection = imageUrl.openConnection();
            
            // 设置请求头，模拟浏览器访问
            connection.setRequestProperty("User-Agent", 
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
            connection.setRequestProperty("Referer", "https://dashscope.aliyuncs.com/");
            connection.setRequestProperty("Accept", "image/webp,image/apng,image/*,*/*;q=0.8");
            connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
            
            // 读取图片数据
            byte[] imageData = connection.getInputStream().readAllBytes();
            
            // 获取内容类型
            String contentType = connection.getContentType();
            if (contentType == null) {
                // 根据URL扩展名推断内容类型
                if (url.toLowerCase().contains(".png")) {
                    contentType = "image/png";
                } else if (url.toLowerCase().contains(".jpg") || url.toLowerCase().contains(".jpeg")) {
                    contentType = "image/jpeg";
                } else if (url.toLowerCase().contains(".gif")) {
                    contentType = "image/gif";
                } else if (url.toLowerCase().contains(".webp")) {
                    contentType = "image/webp";
                } else {
                    contentType = "image/png"; // 默认
                }
            }
            
            log.info("成功获取图片，大小: {} bytes, 类型: {}", imageData.length, contentType);
            
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType(contentType));
            headers.setContentLength(imageData.length);
            headers.setCacheControl("public, max-age=3600"); // 缓存1小时
            headers.set("Access-Control-Allow-Origin", "*");
            
            return new ResponseEntity<>(imageData, headers, HttpStatus.OK);
            
        } catch (IOException e) {
            log.error("获取图片失败: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        } catch (Exception e) {
            log.error("代理图片异常: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
    
    /**
     * 获取图片的Base64编码
     */
    @GetMapping("/base64")
    public ResponseEntity<String> getImageBase64(@RequestParam String url) {
        try {
            log.info("获取图片Base64: {}", url);
            
            // 验证URL
            if (!url.contains("dashscope-result") || !url.contains("aliyuncs.com")) {
                log.warn("非法的图片URL: {}", url);
                return ResponseEntity.badRequest().body("Invalid URL");
            }
            
            // 创建URL连接
            URL imageUrl = new URL(url);
            URLConnection connection = imageUrl.openConnection();
            
            // 设置请求头
            connection.setRequestProperty("User-Agent", 
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
            connection.setRequestProperty("Referer", "https://dashscope.aliyuncs.com/");
            
            // 读取图片数据
            byte[] imageData = connection.getInputStream().readAllBytes();
            
            // 转换为Base64
            String base64 = Base64.getEncoder().encodeToString(imageData);
            
            // 获取内容类型
            String contentType = connection.getContentType();
            if (contentType == null) {
                contentType = "image/png";
            }
            
            // 构造Data URL
            String dataUrl = "data:" + contentType + ";base64," + base64;
            
            log.info("成功转换图片为Base64，大小: {} bytes", imageData.length);
            
            return ResponseEntity.ok(dataUrl);
            
        } catch (Exception e) {
            log.error("获取图片Base64失败: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("Failed to get image: " + e.getMessage());
        }
    }
}
